﻿using System.Reflection;
using WenAntdUI.Helps;

namespace WenAntdUI.Components;

[ToolboxItem(false)]
public partial class MenuControlTypeSelect : UserControl
{
    private string value;
    public MenuControlTypeSelect()
    {
        InitializeComponent();
        var items = new List<SItem>();
        foreach (var item in App.Services)
        {
            var type = item.ServiceType;
            if (type.IsSubclassOf(typeof(Control)) && !type.IsSubclassOf(typeof(Form)))
            {
                var name = type.GetCustomAttribute<DescriptionAttribute>()?.Description ?? type.Name;
                items.Add(new SItem(name, type.AssemblyQualifiedName));
            }
        }
        this.select1.Items.Add(new SItem("无控件", ""));
        this.select1.Items.AddRange([.. items]);


        this.select1.SelectedValueChanged += (s, e) => Value = ((SItem)e.Value).Value;//ValueChanged?.Invoke(this, ((SItem)e.Value).Value);
    }
    public string Value
    {
        get => value;
        set
        {
            if (value != this.value)
            {
                SetValue(value);
                this.OnPropertyChanged(t => t.Value);
            }
        }
    }

    public void SetValue(object value)
    {
        var type = Type.GetType((string)value);
        var selectItem = this.select1.Items.ToList<SItem>().FirstOrDefault(x => x.Value == value?.ToString());
        this.select1.SelectedValue = selectItem;
        //this.select1.Text = type?.GetCustomAttribute<DescriptionAttribute>()?.Description ?? type?.Name ?? "";
        this.value = value?.ToString() ?? "";
    }

    public class SItem
    {
        public SItem(string name, string value)
        {
            Name = name;
            Value = value;
        }

        public string Name { get; set; }
        public string Value { get; set; }

        public override string ToString() => Name;
    }
}
